package com.wwj.auction.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.admin.entity.TransFlow;
import com.wwj.auction.admin.entity.UserAccount;
import com.wwj.auction.admin.entity.Withdraw;
import com.wwj.auction.admin.entity.vo.PageModel;
import com.wwj.auction.admin.entity.vo.WithdrawVo;
import com.wwj.auction.admin.enums.AuditStatus;
import com.wwj.auction.admin.enums.TransFlowType;
import com.wwj.auction.admin.mapper.TransFlowMapper;
import com.wwj.auction.admin.mapper.UserAccountMapper;
import com.wwj.auction.admin.mapper.WithdrawMapper;
import com.wwj.auction.admin.service.WithdrawService;
import com.wwj.auction.common.util.SystemUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-25
 */
@Service
public class WithdrawServiceImpl extends ServiceImpl<WithdrawMapper, Withdraw> implements WithdrawService {

    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private TransFlowMapper transFlowMapper;

    @Override
    public PageModel<WithdrawVo> list(Integer page, Integer limit, String keyword) {
        LambdaQueryWrapper<Withdraw> wrapper = Wrappers.lambdaQuery(Withdraw.class);
        // 判断是否有查询条件
        if (!StringUtils.isEmpty(keyword)) {
            // 拼接查询条件
            wrapper.like(Withdraw::getUserName, keyword)
                    .or()
                    .like(Withdraw::getPhone, keyword)
                    .or()
                    .like(Withdraw::getIdCard, keyword);
        }
        // 按照id降序，使之总是能够得到最新的数据
        wrapper.orderByDesc(Withdraw::getId);
        // 执行分页流程
        Page<Withdraw> withdrawPage = new Page<>(page, limit);
        List<Withdraw> withdrawList = baseMapper.selectPage(withdrawPage, wrapper).getRecords();
        // 封装Vo
        List<WithdrawVo> withdrawVoList = withdrawList.stream().map(withdraw -> {
            WithdrawVo withdrawVo = new WithdrawVo();
            // 属性拷贝
            BeanUtils.copyProperties(withdraw, withdrawVo);
            // 处理日期时间
            LocalDateTime localDateTime = withdraw.getCreateTime();
            String time = SystemUtil.parseDate(localDateTime);
            withdrawVo.setCreateTime(time);
            return withdrawVo;
        }).collect(Collectors.toList());
        // 封装最终返回结果
        PageModel<WithdrawVo> pageModel = new PageModel<>();
        pageModel.setList(withdrawVoList);
        pageModel.setTotal(withdrawPage.getTotal());
        return pageModel;
    }

    @Override
    public void changeStatus(Integer id, Integer status) {
        // 查询当前提现内容
        Withdraw withdraw = baseMapper.selectById(id);
        // 设置提现状态
        withdraw.setStatus(status);
        // 更新
        baseMapper.updateById(withdraw);

        // 取出用户id
        Integer userId = withdraw.getUserId();
        // 查询用户账户信息
        UserAccount userAccount = userAccountMapper.selectOne(
                Wrappers.lambdaQuery(UserAccount.class)
                        .eq(UserAccount::getUserId, userId));
        // 获取余额
        BigDecimal amount = userAccount.getAmount();
        // 获取冻结金额
        BigDecimal freezeAmount = userAccount.getFreezeAmount();
        // 当管理员点击拒绝后，需要将冻结的金额解冻，并重新加回用户的余额中
        if (status.equals(AuditStatus.AUDIT_DISAGREE.getStatus())) {
            // 将冻结金额加回到余额中
            userAccount.setAmount(amount.add(freezeAmount));
            // 冻结金额清零
            userAccount.setFreezeAmount(new BigDecimal("0"));

            // 记录交易流水
            TransFlow transFlow = new TransFlow();
            transFlow.setUserId(userId);
            String transNo = UUID.randomUUID().toString().replaceAll("-", "");
            transFlow.setTransNo(transNo);
            transFlow.setTransType(TransFlowType.FREEZE_RETURN.getStatus());
            transFlow.setTransTypeName(TransFlowType.FREEZE_RETURN.getMsg());
            transFlow.setTransAmount(freezeAmount);
            transFlow.setCreateTime(LocalDateTime.now());
            transFlowMapper.insert(transFlow);

        } else if (status.equals(AuditStatus.AUDIT_AGREE.getStatus())) {
            // 管理员若是同意了提现请求，则需将冻结金额存入第三方账户并清零

            // TODO 将冻结金额存入支付宝账户，即可完成提现
            // ......

            // 冻结金额清零
            userAccount.setFreezeAmount(new BigDecimal("0"));

            // 记录交易流水
            TransFlow transFlow = new TransFlow();
            transFlow.setUserId(userId);
            String transNo = UUID.randomUUID().toString().replaceAll("-", "");
            transFlow.setTransNo(transNo);
            transFlow.setTransType(TransFlowType.WITHDRAW_DEPOSIT.getStatus());
            transFlow.setTransTypeName(TransFlowType.WITHDRAW_DEPOSIT.getMsg());
            transFlow.setTransAmount(freezeAmount);
            transFlow.setCreateTime(LocalDateTime.now());
            transFlowMapper.insert(transFlow);
        }
        // 更新
        userAccountMapper.updateById(userAccount);
    }
}
